import { CodecType, U8 } from "./codec";
import { errMsg, err_msg_info } from "./ec";

export interface IMessage {
    buf: number[],
}

export class Message {

    buf: number[];

    constructor(msg: IMessage) {
        this.buf = msg.buf;
    }

    assert() {
        const ec = new U8();
        this.parseResponse(ec);
        if (ec.value != 0) {
            throw err_msg_info(this.src(), ec.value);
        }
    }

    parseResponse(...args: CodecType[]) {
        let index = 8;
        for (const arg of args) {
            arg.decode(this.buf, index);
            index += arg.size();
        }
    }

    parseResult(...args: CodecType[]) {
        let index = 7;
        for (const arg of args) {
            arg.decode(this.buf, index);
            index += arg.size();
        }
    }

    src() {
        return this.buf[3];
    }

    dst() {
        return this.buf[4];
    }

    types() {
        return this.buf[5];
    }

    seq() {
        return this.buf[6];
    }

    query_result_cmd() {
        return this.buf[6];
    }

    req_res_notify_ack_cmd() {
        return this.buf[7];
    }
}
